using System.Text;
using CampusDataOperationLibrary;
using CampusModel;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using PublicProject.Filters;
using PublicProject.PublicClass.Basics;
using PublicProject.PublicMethods;
using Swashbuckle.AspNetCore.SwaggerGen;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();

// 注册dbcontext
builder.Services.AddDbContext<CampusModelDbContext>(
    c => c.UseSqlServer
        ("server=127.0.0.1,1433;database=CampusSystemDatabase;User ID=sa;Password=Aa123456789@;Trusted_Connection=false;Encrypt=False"));

//启用Swagger中的【Authorize】按钮。这样就不用每个项目的AddSwaggerGen中单独配置了
builder.Services.Configure<SwaggerGenOptions>(o =>
{
    o.AddAuthenticationHeader();
});

// 注册过滤器器
builder.Services.Configure<MvcOptions>(o => { o.Filters.Add<ExceptionFilter>(); });

// 添加 Swagger 生成器服务
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new OpenApiInfo
    {
        Title = "Campus System Service API",
        Version = "v1",
        Description = "Campus System Service API",
    });
});

//JWT
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(x =>
{
    var jwtOpt = new JWTOption();
    // 获取JWT秘钥
    byte[] keyBytes = Encoding.UTF8.GetBytes(jwtOpt.Key!);
    // 创建SymmetricSecurityKey
    var secKey = new SymmetricSecurityKey(keyBytes);
    // 设置TokenValidationParameters
    x.TokenValidationParameters = new()
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = jwtOpt.Issuer,
        ValidAudience = jwtOpt.Audience,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOpt.Key))
    };
});

// 注册基础服务
builder.Services.AddScoped<LoginOperation>();
builder.Services.AddScoped<TeacherCourseOperation>();
builder.Services.AddScoped<StudentOperation>();
builder.Services.AddScoped<AdminOperation>();
//配置跨域
builder.Services.AddCors(o => { o.AddDefaultPolicy(builder => { builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod(); }); });
//注册返回httresponse服务
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
BaseHttpContext.ServiceCollection = builder.Services;

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.MapOpenApi();
}

// app.UseHttpsRedirection();

// 使用 Swagger 中间件
app.UseSwagger();
app.UseSwaggerUI(options =>
{
    options.SwaggerEndpoint("/swagger/v1/swagger.json", "My Web API V1");
    options.RoutePrefix = string.Empty; // 设置 Swagger UI 的根路径
});
app.UseCors();
//启动JWT
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

// Create hardcoded admin user during startup
using (var scope = app.Services.CreateScope())
{
    var dbContext = scope.ServiceProvider.GetRequiredService<CampusModelDbContext>();

    // Check if admin user already exists
    if (!dbContext.Users.Any(u => u.Role == CampusModel.Enum.UserRole.Admin))
    {
        // Create admin entity
        var admin = new CampusModel.Model.Admin("admin");
        dbContext.Admins.Add(admin);
        dbContext.SaveChanges();

        // Create admin user
        var adminUser = new CampusModel.Model.User(
            CampusModel.Enum.UserRole.Admin,
            "admin",
            "admin123",
            admin.Id
        );
        dbContext.Users.Add(adminUser);
        dbContext.SaveChanges();

        Console.WriteLine("Hardcoded admin user created successfully.");
    }
    else
    {
        Console.WriteLine("Admin user already exists.");
    }
}

app.Run();